package cn.com.nes.common.baiduface;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.node.ObjectNode;

public final class BaiduApis {
	
	private static RestTemplate template = new RestTemplate();
	
	public static ObjectNode getToken(String clientId, String clientSecret) {
		String url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={clientId}&client_secret={clientSecret}";
		return template.postForObject(url, HttpEntity.EMPTY, ObjectNode.class, clientId, clientSecret);
	}
	
	public static ObjectNode getVerifyToken(String accessToken, Integer planId) {
		String url = "https://aip.baidubce.com/rpc/2.0/brain/solution/faceprint/verifyToken/generate?access_token={accessToken}";
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		HttpEntity<String> request = new HttpEntity<String>("{ \"plan_id\": " + planId + " }", headers);
		return template.postForObject(url, request, ObjectNode.class, accessToken);
	}
	
	public static ObjectNode getFaceImage(String accessToken, String verifyToken) {
		String url = "https://aip.baidubce.com/rpc/2.0/brain/solution/faceprint/result/simple?access_token={accessToken}";
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		HttpEntity<String> request = new HttpEntity<String>("{ \"verify_token\": \"" + verifyToken + "\" }", headers);
		return template.postForObject(url, request, ObjectNode.class, accessToken);
	}
	
	public static ObjectNode getFaceDetail(String accessToken, String verifyToken) {
		String url = "https://aip.baidubce.com/rpc/2.0/brain/solution/faceprint/result/detail?access_token={accessToken}";
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		HttpEntity<String> request = new HttpEntity<String>("{ \"verify_token\": \"" + verifyToken + "\" }", headers);
		return template.postForObject(url, request, ObjectNode.class, accessToken);
	}
	
	public static ObjectNode getFaceStat(String accessToken, String verifyToken) {
		String url = "https://aip.baidubce.com/rpc/2.0/brain/solution/faceprint/result/stat?access_token={accessToken}";
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		HttpEntity<String> request = new HttpEntity<String>("{ \"verify_token\": \"" + verifyToken + "\" }", headers);
		return template.postForObject(url, request, ObjectNode.class, accessToken);
	}
	
	public static byte[] getBytes(String url) {
		byte[] stream = template.getForObject(url, byte[].class);
		return stream;
	}

}
